<template>
  <div ref="container" :style="containerStyle"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import loader from '@monaco-editor/loader';

const props = defineProps({
  modelValue: String,
  language: { type: String, default: 'javascript' },
  theme: { type: String, default: 'vs' },
  height: { type: [String, Number], default: '500px' }
});

const emit = defineEmits(['update:modelValue']);

const container = ref(null);
const containerStyle = ref({ height: props.height, width: '100%' });
let editor = null;
const codeLanguage = ref('css')
// 初始化编辑器
const initEditor = async () => {
  loader.config({ paths: { vs: `${import.meta.env.BASE_URL}/assets/monaco/vs` } })
  const monaco = await loader.init();
  editor = monaco.editor.create(container.value, {
    value: props.modelValue,
    language: props.language,
    theme: props.theme,
    automaticLayout: true
  });
  // 监听内容变化
  editor.onDidChangeModelContent(() => {
    const value = editor.getValue();
    emit('update:modelValue', value);
  });
};

// 监听属性变化
watch(() => props.language, (val) => {
  monaco.editor.setModelLanguage(editor.getModel(), val);
});

watch(() => props.theme, (val) => {
  monaco.editor.setTheme(val);
});
onMounted(() => {
  initEditor()
})
onUnmounted(() => {
  editor?.dispose()
});
</script>
